package com.fqcar.fqdf.ui;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.android.volley.Response;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.fqcar.fqdf.DFApp;
import com.fqcar.fqdf.R;
import com.fqcar.fqdf.core.BaseRequestActivity;
import com.fqcar.fqdf.entity.CarDetailRespBean;
import com.fqcar.fqdf.service.RequestOptService;
//import com.fqcar.fqdf.ui.chargemap.StubHomeActivity;
import com.fqcar.fqdf.util.Constants;
import com.fqcar.fqdf.util.DialogUtil;
import com.fqcar.fqdf.util.NavigationUtils;
import com.fqcar.fqdf.util.ReqConstants;
import com.fqdf.framework.android.net.response.NetBaseWrapper;
import com.fqdf.framework.android.net.response.NetBeanWrapper;
import com.fqdf.framework.android.util.AndroidUtils;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by lvsidong on 2017/10/25.
 */

public class CarDetailActivity extends BaseRequestActivity implements OnGetGeoCoderResultListener {

    @BindView(R.id.main_back_iv)
    ImageView mainBackIv;
    @BindView(R.id.car_detail_plate_num)
    TextView carDetailPlateNum;
    @BindView(R.id.car_detail_brand)
    TextView carDetailBrand;
    @BindView(R.id.car_detail_history)
    Button carDetailHistory;
    @BindView(R.id.top)
    RelativeLayout top;
    @BindView(R.id.main_car_mileage)
    TextView mainCarMileage;
    @BindView(R.id.main_car_battery)
    TextView mainCarBattery;
    @BindView(R.id.main_car_charge_state)
    TextView mainCarChargeState;
    @BindView(R.id.main_car_machine_state)
    TextView mainCarMachineState;
    @BindView(R.id.main_car_state)
    TextView mainCarState;
    @BindView(R.id.car_detail_info_layout)
    RelativeLayout carDetailInfoLayout;
    @BindView(R.id.car_detail_parking_name)
    TextView carDetailParkingName;
    @BindView(R.id.car_detail_location_address)
    TextView carDetailLocationAddress;
    @BindView(R.id.car_detail_distance)
    TextView carDetailDistance;
    @BindView(R.id.car_detail_nav_iv)
    ImageView carDetailNavIv;
    @BindView(R.id.car_detail_nav_layout)
    LinearLayout carDetailNavLayout;
    @BindView(R.id.car_detail_location_layout)
    RelativeLayout carDetailLocationLayout;
    @BindView(R.id.car_detail_open_door)
    Button carDetailOpenDoor;
    @BindView(R.id.car_detail_find_car_sound)
    Button carDetailFindCarSound;
    @BindView(R.id.car_detail_charge)
    Button carDetailCharge;
    @BindView(R.id.car_detail_close_door)
    Button carDetailCloseDoor;
    @BindView(R.id.car_detail_control_layout)
    LinearLayout carDetailControlLayout;
    @BindView(R.id.car_detail_take_photo)
    Button carDetailTakePhoto;
    @BindView(R.id.car_detail_turn_on)
    Button carDetailTurnOn;
    @BindView(R.id.car_detail_turn_off)
    Button carDetailTurnOff;
    @BindView(R.id.car_detail_finish_online)
    Button carDetailFinishOnline;
    @BindView(R.id.car_detail_finish_offline)
    Button carDetailFinishOffline;
    @BindView(R.id.car_detail_offline)
    Button carDetailOffline;
    @BindView(R.id.car_detail_modify_position)
    Button carDetailModifyPosition;

    private int carId;
    private String carLicense;
    private BDLocation location = null;
    private CarDetailRespBean carDetailRespBean;
    private GeoCoder geoCoder;

    public MaterialDialog openDoorDialog;
    public MaterialDialog closeDoorDialog;
    public MaterialDialog turnOnDialog;
    public MaterialDialog turnOffDialog;
    public MaterialDialog finishOnlineDialog;
    public MaterialDialog finishOfflineDialog;
    public MaterialDialog offlineDialog;
    public MaterialDialog gpsDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_car_detail);
        ButterKnife.bind(this);

        geoCoder = GeoCoder.newInstance();
        geoCoder.setOnGetGeoCodeResultListener(this);

//        carId = getIntent().getIntExtra(Constants.BUNDLE_DATA,0);
        location = ((DFApp) getApplication()).getCurLocation();
        requestCarInfo();
    }

    private void openDoor() {//二次确认
        getProgressDialog().show();
        RequestOptService.carControl(CarDetailActivity.this, carId, getString(R.string.car_control_open_door), location.getLatitude(), location.getLongitude(), new Response.Listener<NetBaseWrapper>() {
            @Override
            public void onResponse(NetBaseWrapper response) {
                getProgressDialog().dismiss();
                if (!handleResponse(response)) {
                    DialogUtil.ToastMessage(CarDetailActivity.this, "开门指令发送成功");
                }
            }
        }, getDefaultErrorListener());
    }

    private void findCar() {
        getProgressDialog().show();
        RequestOptService.carControl(CarDetailActivity.this, carId, getString(R.string.car_control_find_car), location.getLatitude(), location.getLongitude(), new Response.Listener<NetBaseWrapper>() {
            @Override
            public void onResponse(NetBaseWrapper response) {
                getProgressDialog().dismiss();
                if (!handleResponse(response)) {
                    DialogUtil.ToastMessage(CarDetailActivity.this, "寻车指令发送成功");
                }
            }
        }, getDefaultErrorListener());
    }

    private void charge() {
        if (AndPermission.hasPermission(this, Manifest.permission.CAMERA)) {
            Intent intent = new Intent(CarDetailActivity.this, QRCaptureActivity.class);
            intent.putExtra(Constants.BUNDLE_DATA, carId);
            startActivity(intent);
//            finish();
        } else {
            // 申请权限。
            AndPermission.with(this)
                    .requestCode(ReqConstants.REQUEST_CODE_FOR_CAMERA)
                    .permission(Manifest.permission.CAMERA)
                    .send();
        }
    }

    private void closeDoor() {//二次确认
        RequestOptService.carControl(CarDetailActivity.this, carId, getString(R.string.car_control_close_door), location.getLatitude(), location.getLongitude(), new Response.Listener<NetBaseWrapper>() {
            @Override
            public void onResponse(NetBaseWrapper response) {
                if (!handleResponse(response)) {
                    DialogUtil.ToastMessage(CarDetailActivity.this, "关门指令发送成功");
                }
            }
        }, getDefaultErrorListener());
    }

    private void takePhoto() {
        Intent history_intent = new Intent(CarDetailActivity.this, HistoryCarListActivity.class);
        history_intent.putExtra(com.fqcar.fqdf.util.Constants.BUNDLE_DATA, carId);
        history_intent.putExtra(com.fqcar.fqdf.util.Constants.BUNDLE_DATA_EXT, carLicense);
        CarDetailActivity.this.startActivity(history_intent);
    }

    private void turnOn() {//二次确认
        getProgressDialog().show();
        RequestOptService.carControl(CarDetailActivity.this, carId, getString(R.string.car_control_turn_on), location.getLatitude(), location.getLongitude(), new Response.Listener<NetBaseWrapper>() {
            @Override
            public void onResponse(NetBaseWrapper response) {
                getProgressDialog().dismiss();
                if (!handleResponse(response)) {
                    DialogUtil.ToastMessage(CarDetailActivity.this, "通电指令发送成功");
                }
            }
        }, getDefaultErrorListener());
    }

    private void turnOff() {//二次确认
        getProgressDialog().show();
        RequestOptService.carControl(CarDetailActivity.this, carId, getString(R.string.car_control_turn_off), location.getLatitude(), location.getLongitude(), new Response.Listener<NetBaseWrapper>() {
            @Override
            public void onResponse(NetBaseWrapper response) {
                getProgressDialog().dismiss();
                if (!handleResponse(response)) {
                    DialogUtil.ToastMessage(CarDetailActivity.this, "断电指令发送成功");
                }
            }
        }, getDefaultErrorListener());
    }

    private void finishOnline() {//二次确认
        getProgressDialog().show();
        RequestOptService.endDealAndOnLine(CarDetailActivity.this, carId, location.getLatitude(), location.getLongitude(), new Response.Listener<NetBaseWrapper>() {
            @Override
            public void onResponse(NetBaseWrapper response) {
                getProgressDialog().dismiss();
                if (!handleResponse(response)) {
                    DialogUtil.ToastMessage(CarDetailActivity.this, "操作成功");
                    Intent intent = new Intent(CarDetailActivity.this, NormalHomeActivity.class);
                    intent.setAction(com.fqcar.fqdf.util.Constants.Action.HOME_REFRESH_ACTION);
                    startActivity(intent);
                }
            }
        }, getDefaultErrorListener());
    }

    private void finishOffline() {//二次确认
        Intent intent = new Intent(CarDetailActivity.this, EndDealWithProblemsActivity.class);
        intent.putExtra(Constants.BUNDLE_DATA, carId);
        startActivity(intent);

    }

    /**
     * 手动下线
     */
    private void offline() {
        getProgressDialog().show();
        RequestOptService.offLine(CarDetailActivity.this, carId, location.getLatitude(), location.getLongitude(), new Response.Listener<NetBaseWrapper>() {
            @Override
            public void onResponse(NetBaseWrapper response) {
                getProgressDialog().dismiss();
                if (!handleResponse(response)) {
                    requestCarInfo();
                    DialogUtil.ToastMessage(CarDetailActivity.this, "操作成功");
                }
            }
        }, getDefaultErrorListener());
    }

    private void requestCarInfo() {
        getProgressDialog().show();
        RequestOptService.getDealDetailPage(this, new Response.Listener<NetBeanWrapper<CarDetailRespBean>>() {
            @Override
            public void onResponse(NetBeanWrapper<CarDetailRespBean> response) {
                getProgressDialog().dismiss();
                if (handleBeanResponse(response)) {
                    return;
                }
                carDetailRespBean = response.getModelData();
                carId = carDetailRespBean.getCarVo().getCarId();
                carLicense = carDetailRespBean.getCarVo().getCarNum();
                LatLng latLng = new LatLng(carDetailRespBean.getCarVo().getLatitude(), carDetailRespBean.getCarVo().getLongitude());
                ReverseGeoCodeOption reverseGeoCodeOption = new ReverseGeoCodeOption().location(latLng);
                geoCoder.reverseGeoCode(reverseGeoCodeOption);

                updateView();
            }
        }, getDefaultErrorListener());
    }

    private void updateView() {
        carDetailPlateNum.setText(carDetailRespBean.getCarVo().getCarNum());
        carDetailBrand.setText(carDetailRespBean.getCarVo().getBrand());
        mainCarMileage.setText(carDetailRespBean.getCarVo().getRemainMileageDesc());
        mainCarBattery.setText(carDetailRespBean.getCarVo().getPowerDesc());
        mainCarChargeState.setText(carDetailRespBean.getCarVo().getChargeStatusDesc());
        mainCarMachineState.setText(carDetailRespBean.getCarVo().getOnlineStatusDesc());
        mainCarState.setText(carDetailRespBean.getCarVo().getStatusDesc());
//        carDetailParkingName.setText("归属站点：" + carDetailRespBean.getCarVo().getInStationName());
        carDetailDistance.setText(carDetailRespBean.getCarVo().getDistanceDesc());

        carDetailModifyPosition.setVisibility(carDetailRespBean.getCarVo().getStatus() == Constants.NormalStatus.UNSHOW ? View.VISIBLE : View.GONE);

    }


    @OnClick({R.id.main_back_iv, R.id.car_detail_history, R.id.car_detail_nav_iv, R.id.car_detail_open_door, R.id.car_detail_find_car_sound,
            R.id.car_detail_charge, R.id.car_detail_close_door, R.id.car_detail_take_photo, R.id.car_detail_turn_on, R.id.car_detail_turn_off,
            R.id.car_detail_charge_stub, R.id.car_detail_modify_position,R.id.car_detail_offline, R.id.car_detail_finish_online, R.id.car_detail_finish_offline})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.main_back_iv:
                finish();
                break;
            case R.id.car_detail_history:
                takePhoto();
                break;
            case R.id.car_detail_nav_iv:
                NavigationUtils.showNavigationDialog(CarDetailActivity.this, new LatLng(carDetailRespBean.getCarVo().getLatitude(), carDetailRespBean.getCarVo().getLongitude()),
                        NavigationUtils.Driving, NavigationUtils.ReturnCar, "车辆位置");
                break;
            case R.id.car_detail_open_door:
                if (openDoorDialog == null) {
                    openDoorDialog = new MaterialDialog.Builder(CarDetailActivity.this)
                            .content("确认开门吗？")
                            .positiveText("确定")
                            .negativeText("取消")
                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    openDoor();
                                }
                            })
                            .build();
                    if (!openDoorDialog.isShowing()) {
                        openDoorDialog.show();
                    }
                } else {
                    openDoorDialog.show();
                }
                break;
            case R.id.car_detail_find_car_sound:
                findCar();
                break;
            case R.id.car_detail_charge:
                charge();

                break;
            case R.id.car_detail_close_door:
                if (closeDoorDialog == null) {
                    closeDoorDialog = new MaterialDialog.Builder(CarDetailActivity.this)
                            .content("确认关门吗？")
                            .positiveText("确定")
                            .negativeText("取消")
                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    closeDoor();
                                }
                            })
                            .build();
                    if (!closeDoorDialog.isShowing()) {
                        closeDoorDialog.show();
                    }
                } else {
                    closeDoorDialog.show();
                }
                break;
            case R.id.car_detail_take_photo:
                takePhoto();
                break;
            case R.id.car_detail_turn_on:
                if (turnOnDialog == null) {
                    turnOnDialog = new MaterialDialog.Builder(CarDetailActivity.this)
                            .content("确认通电吗？")
                            .positiveText("确定")
                            .negativeText("取消")
                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    turnOn();
                                }
                            })
                            .build();
                    if (!turnOnDialog.isShowing()) {
                        turnOnDialog.show();
                    }
                } else {
                    turnOnDialog.show();
                }
                break;
            case R.id.car_detail_turn_off:
                if (turnOffDialog == null) {
                    turnOffDialog = new MaterialDialog.Builder(CarDetailActivity.this)
                            .content("确认断电吗？")
                            .positiveText("确定")
                            .negativeText("取消")
                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    turnOff();
                                }
                            })
                            .build();
                    if (!turnOffDialog.isShowing()) {
                        turnOffDialog.show();
                    }
                } else {
                    turnOffDialog.show();
                }
                break;
            case R.id.car_detail_charge_stub:
//                Intent intent = new Intent(CarDetailActivity.this, StubHomeActivity.class);
//                CarDetailActivity.this.startActivity(intent);
                break;
            case R.id.car_detail_modify_position://更改位置

                if(!AndroidUtils.isGpsOPen(CarDetailActivity.this)){
                    if(gpsDialog == null){
                        gpsDialog = new MaterialDialog.Builder(CarDetailActivity.this)
                                .content("请打开GPS")
                                .positiveText("确定")
                                .negativeText("取消")
                                .onNegative(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                        Intent intent_modify = new Intent(CarDetailActivity.this,ModifyCarPosActivity.class);
                                        intent_modify.putExtra(Constants.BUNDLE_DATA,carId);
                                        CarDetailActivity.this.startActivity(intent_modify);
                                    }
                                })
                                .onPositive(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                                        AndPermission.defaultSettingDialog(CarDetailActivity.this, 400).show();
                                        Intent intent = new Intent(
                                                Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                        CarDetailActivity.this.startActivity(intent);
                                    }
                                })
                                .build();
                        if (!gpsDialog.isShowing()) {
                            gpsDialog.show();
                        }
                    }else {
                        gpsDialog.show();
                    }
                }else {
                    Intent intent_modify = new Intent(CarDetailActivity.this,ModifyCarPosActivity.class);
                    intent_modify.putExtra(Constants.BUNDLE_DATA,carId);
                    CarDetailActivity.this.startActivity(intent_modify);
                }

                break;
            case R.id.car_detail_offline:

                if (offlineDialog == null) {
                    offlineDialog = new MaterialDialog.Builder(CarDetailActivity.this)
                            .content("确认下线吗？")
                            .positiveText("确定")
                            .negativeText("取消")
                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    offline();
                                }
                            })
                            .build();
                    if (!offlineDialog.isShowing()) {
                        offlineDialog.show();
                    }
                } else {
                    offlineDialog.show();
                }
                break;
            case R.id.car_detail_finish_online:
                if (finishOnlineDialog == null) {
                    finishOnlineDialog = new MaterialDialog.Builder(CarDetailActivity.this)
                            .content("确认上线吗？")
                            .positiveText("确定")
                            .negativeText("取消")
                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    finishOnline();
                                }
                            })
                            .build();
                    if (!finishOnlineDialog.isShowing()) {
                        finishOnlineDialog.show();
                    }
                } else {
                    finishOnlineDialog.show();
                }
                break;
            case R.id.car_detail_finish_offline:
                if (finishOfflineDialog == null) {
                    finishOfflineDialog = new MaterialDialog.Builder(CarDetailActivity.this)
                            .content("确认不上线吗？")
                            .positiveText("确定")
                            .negativeText("取消")
                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    finishOffline();
                                }
                            })
                            .build();
                    if (!finishOfflineDialog.isShowing()) {
                        finishOfflineDialog.show();
                    }
                } else {
                    finishOfflineDialog.show();
                }
                break;
        }
    }

    @Override
    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
        if (reverseGeoCodeResult == null || reverseGeoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
            //没有检索到结果
        } else {
            carDetailLocationAddress.setText("当前位置：" + reverseGeoCodeResult.getAddress());
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 只需要调用这一句，其它的交给AndPermission吧，最后一个参数是PermissionListener。
        AndPermission.onRequestPermissionsResult(requestCode, permissions, grantResults, listener);
    }

    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, List<String> grantedPermissions) {
            // 权限申请成功回调。
            if (requestCode == ReqConstants.REQUEST_CODE_FOR_CAMERA) {
                Intent intent = new Intent(CarDetailActivity.this, QRCaptureActivity.class);
                intent.putExtra(Constants.BUNDLE_DATA, carId);
                startActivity(intent);
                finish();
            }
        }

        @Override
        public void onFailed(int requestCode, List<String> deniedPermissions) {
            // 权限申请失败回调。
            if (requestCode == ReqConstants.REQUEST_CODE_FOR_CAMERA) {

                DialogUtil.creatBaseNoTitleDialog(CarDetailActivity.this, "我们需要获取相机权限，否则您将无法正常使用" + getResources().getString(R.string.app_name), "设置", "取消")
                        .getBuilder()
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                // 跳转至当前应用程序的设置界面
                                Uri packageURI = Uri.parse("package:" + getPackageName());
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                                startActivity(intent);
                            }
                        })
                        .show();
            }
        }
    };
}
